package com.auxide.cah;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

import org.json.JSONArray;

import com.auxide.util.Logger;
import com.auxide.util.NetworkManager;

public class Game {
	//Singleton pattern
	private Game(){};

	private static class GameHolder {
		public static final Game instance = new Game();
	}

	public static Game getInstance(){
		return GameHolder.instance;
	}
	
	LinkedList<Player> playerList;
	Stack<String> answers;
	Stack<String> questions;
	Player currentPlayer;
	Player localPlayer;
	String currentQuestion;
	ArrayList<String> currentAnswers;
	boolean host;
	
	public int cardsPerPlayer = 5;
	public int answersPerTurn = 2;
	
	public void startGame(boolean host, Stack<String> as, Stack<String> qs){
		this.host = host;
		this.answers = as;
		this.questions = qs;
		
		if(host){
			Collections.shuffle(playerList);
			Collections.shuffle(questions);
			Collections.shuffle(answers);
			
			for(Player p: playerList){
				for(int i = 0; i < cardsPerPlayer; i++){
					p.answers.add(answers.pop());
				}
				
				if(p.host){
					localPlayer = p;
				}
			}
			
			startRound();
		}
	}
	
	private void startRound(){
		setCurrentPlayer(playerList.getFirst());
		currentQuestion = questions.pop();
	}
	
	private void setCurrentPlayer(Player p){
		currentPlayer = p;
		currentPlayer.setCurrent(true);
		playerList.add(p);
	}
	
	public void endRound(){
		//reset stuff
		for(Player p: playerList){
			for(int i = 0; i < answersPerTurn; i++){
				p.answers.add(answers.pop());
			}
		}
		
		startRound();
	}
	
	
	public String calcScore(String chosenAnswer, String question){
		String player = "";
		for(Player p : playerList){
			if(p.getAnswers().contains(chosenAnswer)){
				p.getQuestions().add(question);
				player = p.name;
			}
		}
		
		return player;
	}
	
	public void init(){
		playerList = new LinkedList<Player>();
	}
	
	public Player getLocalPlayer(){
		return localPlayer;
	}
	
	public List<Player> getPlayers(){ return playerList; }
	
	public JSONArray getPlayersAsJSON(){
		JSONArray ja = new JSONArray();
		for(Player p : playerList){
			ja.put(p.toJSON());
		}
		return ja;
	}
	
	public void setPlayersFromJSON(JSONArray ja){
		try{
			for(int i = 0; i < ja.length(); i++){
				Player p = Player.fromJSON(ja.get(i).toString());
				if(p.ip.equals(NetworkManager.getInstance().getLocalIpAddress())){
					localPlayer = p;
				}
				
				if(p.isCurrent()){
					this.currentPlayer = p;
				}
			}
		}catch(Exception e){
			Logger.e(e);
		}
	}
}
